<template>
  <div class="behavior-execution-panel">
    <!-- 工具栏 -->
    <div class="toolbar">
      <a-space>
        <a-button type="primary" @click="showCreateModal">
          <template #icon>
            <IconifyIcon icon="ant-design:play-circle-outlined" />
          </template>
          执行行为
        </a-button>
        <a-button @click="refreshData">
          <template #icon>
            <IconifyIcon icon="ant-design:reload-outlined" />
          </template>
          刷新
        </a-button>
      </a-space>

      <a-space>
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索执行记录"
          style="width: 200px"
          @search="handleSearch"
        />
        <a-select
          v-model:value="filterStatus"
          placeholder="执行状态"
          style="width: 150px"
          @change="handleFilter"
        >
          <a-select-option value="">全部状态</a-select-option>
          <a-select-option
            v-for="status in executionStatuses"
            :key="status.value"
            :value="status.value"
          >
            {{ status.label }}
          </a-select-option>
        </a-select>
      </a-space>
    </div>

    <!-- 执行记录列表 -->
    <a-table
      :columns="columns"
      :data-source="executions"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusLabel(record.status) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'progress'">
          <a-progress
            :percent="record.progress"
            :status="getProgressStatus(record.status)"
            size="small"
          />
        </template>

        <template v-else-if="column.key === 'actions'">
          <a-space>
            <a-button type="link" size="small" @click="showDetailModal(record)">
              详情
            </a-button>
            <a-button
              v-if="record.status === 'RUNNING'"
              type="link"
              size="small"
              @click="handleCancel(record.id)"
            >
              取消
            </a-button>
            <a-button
              v-if="record.status === 'FAILED'"
              type="link"
              size="small"
              @click="handleRetry(record.id)"
            >
              重试
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 执行详情模态框 -->
    <a-modal
      :open="detailModalVisible"
      title="执行详情"
      width="800px"
      @cancel="closeDetailModal"
      :footer="null"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="执行ID">{{
          selectedExecution?.id
        }}</a-descriptions-item>
        <a-descriptions-item label="行为名称">{{
          selectedExecution?.behaviorName
        }}</a-descriptions-item>
        <a-descriptions-item label="执行状态">
          <a-tag :color="getStatusColor(selectedExecution?.status)">
            {{ getStatusLabel(selectedExecution?.status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="开始时间">{{
          selectedExecution?.startTime
        }}</a-descriptions-item>
        <a-descriptions-item label="结束时间">{{
          selectedExecution?.endTime || '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="执行时长">{{
          selectedExecution?.duration || '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="进度">
          <a-progress
            :percent="selectedExecution?.progress || 0"
            :status="getProgressStatus(selectedExecution?.status)"
          />
        </a-descriptions-item>
        <a-descriptions-item label="重试次数">{{
          selectedExecution?.retryCount || 0
        }}</a-descriptions-item>
      </a-descriptions>

      <a-divider />

      <a-tabs>
        <a-tab-pane key="logs" tab="执行日志">
          <a-timeline>
            <a-timeline-item
              v-for="log in selectedExecution?.logs || []"
              :key="log.id"
              :color="getLogColor(log.level)"
            >
              <p>{{ log.message }}</p>
              <p style="color: #999; font-size: 12px">{{ log.timestamp }}</p>
            </a-timeline-item>
          </a-timeline>
        </a-tab-pane>

        <a-tab-pane key="params" tab="执行参数">
          <a-descriptions :column="1" bordered>
            <a-descriptions-item
              v-for="(value, key) in selectedExecution?.parameters || {}"
              :key="key"
              :label="key"
            >
              {{ value }}
            </a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>

        <a-tab-pane key="result" tab="执行结果">
          <pre>{{ JSON.stringify(selectedExecution?.result, null, 2) }}</pre>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

// Props
interface Props {
  resourceId: string;
  resourceType: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  'execution-created': [execution: any];
  'execution-cancelled': [executionId: string];
  'execution-retried': [executionId: string];
}>();

// 响应式数据
const loading = ref(false);
const executions = ref<any[]>([]);
const searchKeyword = ref('');
const filterStatus = ref('');
const detailModalVisible = ref(false);
const selectedExecution = ref<any>(null);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 执行状态选项
const executionStatuses = computed(() => [
  { value: 'PENDING', label: '等待中' },
  { value: 'RUNNING', label: '执行中' },
  { value: 'SUCCESS', label: '成功' },
  { value: 'FAILED', label: '失败' },
  { value: 'CANCELLED', label: '已取消' },
  { value: 'TIMEOUT', label: '超时' },
]);

// 表格列定义
const columns = [
  {
    title: '执行ID',
    dataIndex: 'id',
    key: 'id',
    width: 120,
  },
  {
    title: '行为名称',
    dataIndex: 'behaviorName',
    key: 'behaviorName',
    width: 200,
  },
  {
    title: '执行状态',
    dataIndex: 'status',
    key: 'status',
    width: 120,
  },
  {
    title: '进度',
    dataIndex: 'progress',
    key: 'progress',
    width: 150,
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    key: 'startTime',
    width: 180,
    customRender: ({ text }: { text: string }) =>
      new Date(text).toLocaleString(),
  },
  {
    title: '执行时长',
    dataIndex: 'duration',
    key: 'duration',
    width: 120,
    customRender: ({ text }: { text: number }) => (text ? `${text}秒` : '-'),
  },
  {
    title: '重试次数',
    dataIndex: 'retryCount',
    key: 'retryCount',
    width: 100,
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
  },
];

// 方法
const loadData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        id: 'exec-001',
        behaviorName: '资源启动',
        status: 'SUCCESS',
        progress: 100,
        startTime: new Date(Date.now() - 300000).toISOString(),
        endTime: new Date(Date.now() - 240000).toISOString(),
        duration: 60,
        retryCount: 0,
        logs: [
          {
            id: '1',
            level: 'INFO',
            message: '开始执行资源启动',
            timestamp: '2024-01-01 10:00:00',
          },
          {
            id: '2',
            level: 'INFO',
            message: '资源启动成功',
            timestamp: '2024-01-01 10:01:00',
          },
        ],
        parameters: { resourceId: 'res-001', timeout: 30 },
        result: { success: true, message: '资源启动成功' },
      },
      {
        id: 'exec-002',
        behaviorName: '资源备份',
        status: 'RUNNING',
        progress: 45,
        startTime: new Date(Date.now() - 60000).toISOString(),
        retryCount: 0,
        logs: [
          {
            id: '1',
            level: 'INFO',
            message: '开始执行资源备份',
            timestamp: '2024-01-01 10:05:00',
          },
          {
            id: '2',
            level: 'INFO',
            message: '正在备份数据...',
            timestamp: '2024-01-01 10:05:30',
          },
        ],
        parameters: { resourceId: 'res-001', backupType: 'full' },
        result: null,
      },
      {
        id: 'exec-003',
        behaviorName: '资源配置',
        status: 'FAILED',
        progress: 30,
        startTime: new Date(Date.now() - 900000).toISOString(),
        endTime: new Date(Date.now() - 870000).toISOString(),
        duration: 30,
        retryCount: 2,
        logs: [
          {
            id: '1',
            level: 'INFO',
            message: '开始执行资源配置',
            timestamp: '2024-01-01 09:45:00',
          },
          {
            id: '2',
            level: 'ERROR',
            message: '配置参数无效',
            timestamp: '2024-01-01 09:45:30',
          },
        ],
        parameters: { resourceId: 'res-001', config: 'invalid' },
        result: { success: false, error: '配置参数无效' },
      },
    ];

    executions.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    message.error('加载执行记录失败');
    console.error('加载执行记录失败:', error);
  } finally {
    loading.value = false;
  }
};

const refreshData = () => {
  loadData();
};

const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

const handleFilter = () => {
  pagination.current = 1;
  loadData();
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

const showCreateModal = () => {
  message.info('执行行为功能开发中...');
};

const showDetailModal = (execution: any) => {
  selectedExecution.value = execution;
  detailModalVisible.value = true;
};

const closeDetailModal = () => {
  detailModalVisible.value = false;
  selectedExecution.value = null;
};

const handleCancel = async (id: string) => {
  try {
    message.success('取消执行成功');
    emit('execution-cancelled', id);
    loadData();
  } catch (error) {
    message.error('取消执行失败');
    console.error('取消执行失败:', error);
  }
};

const handleRetry = async (id: string) => {
  try {
    message.success('重试执行成功');
    emit('execution-retried', id);
    loadData();
  } catch (error) {
    message.error('重试执行失败');
    console.error('重试执行失败:', error);
  }
};

const getStatusLabel = (status: string) => {
  const found = executionStatuses.value.find((s) => s.value === status);
  return found ? found.label : status;foundfound.labelfoundfound.label
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    PENDING: 'default',
    RUNNING: 'processing',
    SUCCESS: 'success',
    FAILED: 'error',
    CANCELLED: 'warning',
    TIMEOUT: 'error',
  };
  return colorMap[status] || 'default';
};

const getProgressStatus = (status: string) => {
  if (status === 'SUCCESS') return 'success';
  if (status === 'FAILED' || status === 'CANCELLED' || status === 'TIMEOUT')
    return 'exception';
  return 'active';
};

const getLogColor = (level: string) => {
  const colorMap: Record<string, string> = {
    INFO: 'blue',
    WARN: 'orange',
    ERROR: 'red',
    DEBUG: 'default',
  };
  return colorMap[level] || 'default';
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style lang="less" scoped>
.behavior-execution-panel {
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
  }

  pre {
    background: #f5f5f5;
    padding: 12px;
    border-radius: 4px;
    font-size: 12px;
    max-height: 300px;
    overflow-y: auto;
  }
}
</style>
